<!--
/**
* Author: linchun
* Date: 2022-07-22 11:12
* Desc: 影院-首页
*/
-->
<template>
  <yy-page class="home-page" :linear-bg="showUser" hasTab>
    <u-sticky bg-color="#fff" offset-top="0" style="top: 0">
      <!-- #ifdef MP-WEIXIN || H5 -->
      <follow-public ref="followPublic"></follow-public>
      <!-- #endif -->
      <view class="top-search-bar flex-b-m">
        <view class="flex-1">
          <cinema-choose></cinema-choose>
        </view>
        <q-rcode />
      </view>
    </u-sticky>
    <zm-mescroll-body ref="mescrollRef" @init="mescrollInit" @down="refresh" @up="upCallback" :sticky="true" :down="downOpt" :up="upOpt">
      <!-- #ifdef MP-WEIXIN || H5 -->
      <invite-user v-if="showUser" ref="inviteUser" :custom-style="{ color: '#fff' }" />
      <!-- #endif -->
      <view class="home-page__content" :class="showTop ? 'pt20' : ''">
        <home-swipe ref="homeSwipe" custom-class="home-swiper mb20" class="" classification="1" :cinema-id="cinemaInfo.cinemaId" />
        <!-- 邀请好友 -->
        <!-- #ifdef MP-WEIXIN || H5 -->
        <invite-activity ref="inviteActivity" />
        <!-- #endif -->
        <view class="film-list">
          <view class="film-list-top">
            <u-tabs
              @click="getFilmData"
              :current="current"
              :active-style="{
                color: '#3BC5D2',
                fontWeight: 'bold',
                fontSize: '15px'
              }"
              :inactive-style="{
                fontWeight: 'bold',
                fontSize: '15px'
              }"
              :list="tabList"
              line-color="#3BC5D2"
              line-height="0"
            ></u-tabs>
            <view class="flex-c-m">
              <view @click="toFilm" class="fs28 lh28 fc3">全部 {{ filmData ? filmData.length : 0 }} </view>
              <u-icon name="arrow-right" color="#333" size="12"></u-icon>
            </view>
          </view>

          <scroll-view class="scroll" scroll-x enable-flex v-if="filmData && filmData.length > 0">
            <view class="scroll-main">
              <view @click="toDetail(item)" class="scroll-item" v-for="(item, index) in filmData" :key="index">
                <zm-image :src="item.cover" radius="8rpx" custom-style="width:144rpx;height:200rpx"></zm-image>
                <view class="one-show mt15 mb10 fc3 fs22 b">{{ item.filmName }}</view>
                <view class="one-show mb10 h40 fc9 fs20">{{ current === 0 ? item.type : item.publishDate }}</view>
                <view v-if="item.preSaleFlag === '0'" class="buy-btn bc-primary" @click.stop="handleBuy(item)">购票</view>
                <view v-if="item.preSaleFlag === '1'" class="buy-btn bc-yellow" @click.stop="handleBuy(item)">预售</view>
              </view>
            </view>
          </scroll-view>
          <view v-else class="scroll flex-c-m flex-col">
            <zm-image src="https://public-oss-file.zmaxfilm.com/applet/img/noData/home-no-movie.png" custom-style="width:209rpx;height:197rpx"></zm-image>
            <view class="fc-gray mt10">暂无排片</view>
          </view>
        </view>
        <view class="goods-list">
          <view>
            <goods-item custom-class="mb20" @click-item="clickGoods(item)" v-for="(item, index) in listData" :key="index" :info="item" />
          </view>
        </view>
      </view>
    </zm-mescroll-body>
  </yy-page>
</template>

<script>
  import listMixins from '@/mixins/newListMixin'
  import ZmImage from '@/commons/ZmImage'
  import ZmMescrollBody from '@/commons/ZmMescrollBody/index.vue'
  import HomeSwipe from '@/components/HomeSwipe'
  import GoodsItem from '@/components/GoodsItem'
  import QRcode from '@/components/QRcode'
  import CinemaChoose from '@/components/CinemaChoose'
  import pageMixins from '@/mixins/pageMixins'
  import sharePage from '@/mixins/sharePage'
  import InviteActivity from './components/InviteActivity.vue'
  // #ifdef MP-WEIXIN || H5
  import FollowPublic from '@/components/FollowPublic/index.vue'
  // #endif
  import InviteUser from '@/components/InviteUser'
  import { mapGetters } from 'vuex'
  import config from '@/config'
  export default {
    mixins: [pageMixins, listMixins, sharePage],
    components: {
      ZmMescrollBody,
      // #ifdef MP-WEIXIN || H5
      FollowPublic,
      // #endif
      InviteUser,
      ZmImage,
      GoodsItem,
      QRcode,
      CinemaChoose,
      HomeSwipe,
      InviteActivity
    },
    data() {
      return {
        pkId: 'mallCommodityId',
        downOpt: {
          textColor: '#fff',
          bgColor: 'linear-gradient(to right, #4fd2cd 0%, #42c7ff 100%)'
        },
        upOpt: {
          empty: {
            type: 'product',
            // bg: '#fff',
            marginTop: '100rpx',
            use: true // 是否显示空布局
          }
        },
        timer: null,
        current: 0,
        tabList: [
          { name: '热映影片', id: 1 },
          { name: '即将上映', id: 2 }
        ],
        filmData: []
      }
    },
    onLoad(options) {
      const router = this.$tools.getCurrentPage()
      const isFromShare = options.sq || options.scene || (router.options && (router.options.sq || router.options.scene))
      if (isFromShare) {
        this.handleShare(router)
      }
    },
    onShow() {
      this.$refs.inviteActivity && this.$refs.inviteActivity.init()
    },

    watch: {
      cinemaId: {
        handler() {
          this.handleInit()
        },
        immediate: true
      },
      memberId: {
        handler() {
          this.handleInit()
        },
        immediate: true
      },
      showUser: {
        handler() {
          console.log(this.showUser, '====showusser')
          if (this.showUser) {
            this.$tools.nextTick(() => {
              this.$refs.inviteUser.init()
            })
          }
        },
        immediate: true
      }
    },
    computed: {
      ...mapGetters(['cinemaId', 'showUser', 'cinemaInfo']),
      showTop() {
        return !this.showUser || config.VUE_APP_PLATFORM === 'mp-alipay'
      }
    },
    methods: {
      updateCinema() {
        // 更新影院信息
        this.$auth.getCinemaInfo(true, 'update')
      },
      handleShare(router) {
        const token = this.$auth.getLocToken()
        if (token) {
          this.timer && clearTimeout(this.timer)
          const info = this.$auth.getShareQuery(router.options)
          // 可能是分享码形式，不存在url要单独处理
          if (info.mallCommodityId) {
            // #ifdef MP-ALIPAY
            this.$nextTick(() => {
              if (!my.canIUse('plugin') && !my.isIDE) {
                console.log('不可用', my.canIUse('plugin'), my.isIDE)
                my.ap && my.ap.updateAlipayClient && my.ap.updateAlipayClient() // 如果动态加载不可用则打开支付宝客户端升级界面
              } else {
                my.reLaunch({
                  url: `plugin://groupPurchaseoucherPlugin/index?outItemId=${item.mallCommodityId}`
                  // outItemId为外部商品id
                })
              }
            })
            // #endif
            // #ifndef MP-ALIPAY
            this.$nextTick(() => {
              this.$tools.navigateTo(
                '/pages/goodDetail/index',
                {
                  mallCommodityId: info.mallCommodityId
                },
                'navigateTo',
                true
              )
            })
            // #endif
          } else {
            // #ifdef MP-WEIXIN || MP-ALIPAY
            if (info.url) {
              const opt = JSON.parse(info.opt)
              this.$tools.nextTick(() => {
                this.$tools.navigateTo(info.url, opt)
              })
            }
            // #endif
          }
        } else {
          this.timer = setTimeout(() => {
            this.handleShare(router)
          }, 100)
        }
      },
      refresh() {
        console.log('触发一次refresh')
        this.handleInit()
      },
      handleInit(refresh = true) {
        // 触发init-防抖
        return this.$utils.debounce(this.init, [refresh])
      },
      init() {
        console.log('刷新init')
        this.updateCinema()
        this.getFilmData()
        this.$tools.nextTick(
          () => {
            this.$refs.homeSwipe.getDataList() //轮播图
            // #ifdef MP-WEIXIN || H5
            this.$refs.followPublic.init()
            // #endif
            this.downCallback()
          },
          ['tt', 'my'],
          500
        )
        this.$refs.inviteActivity && this.$refs.inviteActivity.init()
      },
      listLoad(params) {
        const query = {
          ...this.search,
          ...{ cinemaId: this.cinemaId || '' },
          ...params
        }
        const r = uni.$api.mall.getCommodityList(query)
        return r
      },
      clickGoods(item) {
        // #ifdef MP-ALIPAY
        if (!my.canIUse('plugin') && !my.isIDE) {
          console.log('不可用', my.canIUse('plugin'), my.isIDE)
          my.ap && my.ap.updateAlipayClient && my.ap.updateAlipayClient() // 如果动态加载不可用则打开支付宝客户端升级界面
        } else {
          my.reLaunch({
            url: `plugin://groupPurchaseoucherPlugin/index?outItemId=${item.mallCommodityId}`
            // outItemId为外部商品id
          })
        }
        // #endif
        // #ifndef MP-ALIPAY
        this.$tools.navigateTo('/pages/goodDetail/index', {
          mallCommodityId: item.mallCommodityId
        })
        // #endif
      },
      getFilmData(e) {
        if (e) {
          this.current = e.index
        }
        uni.$api.film[this.current === 0 ? 'getHotFilmList' : 'getPreFilmList']({
          isHome: 'true',
          cinemaId: this.cinemaInfo.cinemaId || ''
        }).then((res) => (this.filmData = res))
      },
      toFilm() {
        this.$tools.navigateTo('/pages/ticket/ticket', {}, 'switchTab')
      },
      toDetail(item) {
        this.$tools.navigateTo(`/subPages/filmDetail/filmDetail`, {
          filmCode: item.filmCode,
          filmId: item.filmId,
          preSaleFlag: item.preSaleFlag
        })
      },

      handleBuy(item) {
        const isSingle = this.$auth.getSingleModel()
        console.log('isSingle', isSingle)
        if (isSingle) {
          // 多影城到影院选择
          const query = this.$utils.encode({
            filmCode: item.filmCode,
            filmName: item.filmName
          })
          this.$tools.navigateTo(`/subPages/selectFilm/selectFilm?query=${query}`)
        } else {
          // 单影城排期页面
          this.$tools.navigateTo(`/subPages/selectCinema/selectCinema`, {
            cinemaId: this.$auth.getLocBaseSet().cinemaId,
            filmCode: item.filmCode,
            planDate: this.$utils.dateFmt(new Date())
          })
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .top-search-bar {
    background: #fff;
    padding: 16rpx 20rpx;
    z-index: 3;
  }
  .home-page {
    &__content {
      padding: 0 20rpx;
    }
  }
  .film-list {
    border-radius: 20rpx;
    background: #fff;
    margin-bottom: 20rpx;
    .film-list-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 30rpx 0 15rpx;
    }
    .scroll {
      height: 380rpx;
      overflow-x: hidden;
      padding: 0 30rpx;
      white-space: nowrap;
      box-sizing: border-box;
      .scroll-main {
        display: flex;
      }
      .scroll-item {
        box-sizing: border-box;
        width: 150rpx;
        // height: 400rpx;
        margin-right: 30rpx;
        display: inline-block;
        .buy-btn {
          width: 72rpx;
          height: 44rpx;
          border-radius: 14rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 22rpx;
        }
      }
    }
  }
</style>
